<template>
    <div>
        <!-- 发布动态表单 -->
        <el-form :model="form" class="post-form">
            <el-card class="form-card">
                <template #header>
                    <div class="form-header">
                        <span>发布动态</span>
                    </div>
                </template>
                <div class="form-body">
                    <el-form-item label="标题" prop="title">
                        <el-input v-model="form.title" placeholder="请输入标题" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="内容" prop="content">
                        <el-input type="textarea" v-model="form.content" placeholder="请输入内容" clearable></el-input>
                    </el-form-item>
                </div>
                <template #footer>
                    <div class="form-footer">
                        <el-button 
                            type="primary" 
                            @click="PostTieziA" 
                            :disabled="postButton" 
                            class="submit-button">发布
                        </el-button>
                        <el-button 
                            @click="resetForm" 
                            class="reset-button">重写
                        </el-button>
                    </div>
                </template>
            </el-card>
        </el-form>
    </div>

    <!-- 动态列表 -->
    <div class="tiezi-list" v-infinite-scroll="loadMore" infinite-scroll-disabled="loading" infinite-scroll-distance="10">
        <div class="list-header">动态列表</div>
        <div v-for="(item, index) in tieziList" :key="index">
            <TieziList :tieziData="item" />
        </div>

        <!-- 加载中提示 -->
        <div v-if="loading" class="loading-indicator">
            加载中...
        </div>
    </div>
</template>

<script setup>
import { nextTick, onMounted, reactive, ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { GetTieziList, PostTiezi } from '@/api/tiezi';
import TieziList from './tieziList.vue';

const postButton = ref(false);
const tieziList = ref([]);
const listPage = ref(1);
const loading = ref(false); // 控制加载状态

const form = ref({
    title: '',
    content: '',
    user_id: ''
})

const PostTieziA = async () => {
    try {
        await nextTick();
        CheckUserID();
        if (postButton.value) return; // 如果按钮被禁用，阻止进一步操作
        const response = await PostTiezi(form.value);
        console.log(form.value);

        const { code, msg, errors, data } = response.data;

        if (code === 200) {
            ElMessage.success(msg); // 成功提示
            
            // 发布成功后将新动态数据推送到动态列表中
            tieziList.value.unshift(data);  // 使用 unshift 将新的动态添加到列表前面

            // 清空表单
            resetForm();
        } else if (code === 400) {
            if (errors) {
                for (const [field, errorMsg] of Object.entries(errors)) {
                    ElMessage.error(`${field}: ${errorMsg}`);  // 显示错误信息
                }
            } else {
                ElMessage.error(msg || '发布失败');
            }
        }
    } catch (error) {
        console.error('Error:', error);
        ElMessage.error('服务器错误，请稍后再试');
    }
}

const getTieziList = async () => {
    const response = await GetTieziList(listPage.value);
    tieziList.value = response.data.data;
    // console.log(tieziList.value);
}

const loadMore = async () => {
    if (loading.value) return; // 防止在加载时重复触发加载

    loading.value = true;
    listPage.value += 1;

    try {
        const response = await GetTieziList(listPage.value);
        const newTieziList = response.data.data;
        if (newTieziList.length > 0) {
            tieziList.value = [...tieziList.value, ...newTieziList]; // 合并已有列表和新加载的列表
        } else {
            ElMessage.info('没有更多动态了');
        }
    } catch (error) {
        console.error('Error:', error);
        ElMessage.error('加载动态失败，请稍后重试');
    } finally {
        loading.value = false;
    }
}

onMounted(() => {
    getTieziList();
})

const CheckUserID = () => {
    const userInfo = JSON.parse(localStorage.getItem('user_info')) || null;
    if (!userInfo) {
        ElMessage.error('请先登录');
        postButton.value = true; // 禁用发布按钮
    } else {
        form.value.user_id = userInfo.id;
        postButton.value = false; // 启用发布按钮
    }
};

const resetForm = () => {
    form.value = {
        title: '',
        content: '',
    }
};
</script>

<style scoped>
/* 表单样式 */
.post-form {
    max-width: 800px;
    margin: 20px auto;
}

.form-card {
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    border-radius: 8px;
    padding: 20px;
    background-color: #fff;
}

.form-header {
    font-size: 1.5rem;
    color: #333;
    font-weight: 500;
    padding: 10px 0;
    border-bottom: 1px solid #ddd;
}

.form-body {
    margin-top: 15px;
}

.el-form-item label {
    font-size: 1.1rem;
    color: #333;
}

.el-input {
    font-size: 1rem;
}

.el-button {
    font-size: 1rem;
    border-radius: 4px;
}

.submit-button {
    background-color: #409EFF;
    color: white;
    padding: 10px 20px;
    margin-right: 10px;
    transition: background-color 0.3s;
}

.submit-button:hover {
    background-color: #66b1ff;
}

.reset-button {
    background-color: #f0f2f5;
    color: #333;
    padding: 10px 20px;
}

.reset-button:hover {
    background-color: #e4e7ed;
}

/* 动态列表 */
.tiezi-list {
    max-width: 800px;
    margin: 20px auto;
    padding: 0 20px;
}

.list-header {
    font-size: 1.4rem;
    color: #333;
    font-weight: 500;
    margin-bottom: 15px;
}

/* 加载中提示 */
.loading-indicator {
    text-align: center;
    padding: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .post-form {
        padding: 15px;
    }

    .form-header {
        font-size: 1.3rem;
    }

    .el-button {
        font-size: 0.9rem;
    }

    .submit-button,
    .reset-button {
        padding: 8px 16px;
    }
}
</style>
